package com.jarich.morewore;

import java.util.ArrayList;

import com.jarich.morewore.model.Weerbericht;
import android.app.Activity;
import android.app.ListActivity;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class Search extends ListActivity {

	private ArrayList<String> list;
	private ArrayAdapter<String> adapter;
	private Weerbericht wb = new Weerbericht();
	private EditText textMessage;
	private WebView wv;
	private TextView tv;
	private String address = "";


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);

		wv = (WebView)findViewById(R.id.weerbericht);
		textMessage = (EditText)findViewById(R.id.searchCityText);
		list = new ArrayList<String>();
		adapter = new ArrayAdapter<String>(this, R.layout.list_item, list);
		setListAdapter(adapter);

		textMessage.addTextChangedListener(new TextWatcher(){
			public void afterTextChanged(Editable s) {}
			public void beforeTextChanged(CharSequence s, int start, int count, int after){
			}
			public void onTextChanged(CharSequence s, int start, int before, int count){
				getCities(s.toString());
			}
		});

		ListView lv = (ListView)findViewById(android.R.id.list);
		lv.setOnItemClickListener(new OnItemClickListener() 
		{
		    @Override
		    public void onItemClick(AdapterView<?> a, View v,int position, long id) 
		    {
		    	GetWOEIDTask gwot = new GetWOEIDTask();
		    	address = list.get(position);
		    	gwot.execute(address);


		    }
		});
	}

	private void showWeerbericht(String html){
		hideKeyboard();
		String s = "<font size='4' color='white'>" + html + "</font>";
		tv =  (TextView)findViewById(R.id.searchText);;
    	tv.setText(address);
    	tv.setVisibility(View.VISIBLE);
		wv.setBackgroundColor(Color.parseColor("#000000"));
		wv.loadData(s, "text/html", "UTF-8");
		wv.setVisibility(0);
	}

	@Override
	public void onBackPressed() {
		wv = (WebView)findViewById(R.id.weerbericht);
		if(wv.getVisibility() != View.GONE){
	    	wv.setVisibility(View.GONE);
	    	tv.setVisibility(View.GONE);
	    	showKeyboard();
		} else {
			Search.super.onBackPressed();
		}
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_search, menu);
        return true;
    }
    
    public void getCities(String filter){
    	GetCitiesTask gct = new GetCitiesTask();
    	gct.execute(filter);
    }
    
    private void updateListView(ArrayList<String> plaatsen){
        try{
        	list.clear();
            for(String s : plaatsen){
            	list.add(s);
            }
            if(list == null || list.isEmpty()){
            	list.add("Plaats niet gevonden");
	    	}
            adapter.notifyDataSetChanged();
        } catch (Exception e){
            System.out.println("ERROR: updateListView()");
            e.printStackTrace(); 
        }
    }
    
    @Override
    protected void onPause(){
    	super.onPause();
    	this.hideKeyboard();
    }
    
    @Override
    protected void onResume(){
    	super.onResume();
    	if(wv.getVisibility() == View.GONE){
    		this.showKeyboard();
    	}
    }
    
    public void showKeyboard()
    {
            InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(0, 0);
        
    }
    
    public void hideKeyboard()
    {
            InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(this.textMessage.getWindowToken(), 0);
        
    }
    
    private class GetCitiesTask extends AsyncTask<String, Void, ArrayList<String>> {

    		@Override
    		protected ArrayList<String> doInBackground(String... params) {
    			return Connector.getCitiesFiltered(params[0]);
    		}
    		
    		@Override
    		protected void onPostExecute(ArrayList<String> param) {
    			updateListView(param);
    	    }
       }
    
    private class GetWOEIDTask extends AsyncTask<String, Void, String> {
       	
       	@Override
        protected void onPostExecute(String param) {
               GetWeerberichtTask gwt = new GetWeerberichtTask();
               gwt.execute(param);
           }

    		@Override
    		protected String doInBackground(String... params) {
    			String woeid = wb.getWOEID(params[0]) + "";
    			System.out.println(woeid);
    			return woeid;
    		}
       }
    
private class GetWeerberichtTask extends AsyncTask<String, Void, String> {
       	
       	@Override
        protected void onPostExecute(String param) {
       		showWeerbericht(param);
           }

    		@Override
    		protected String doInBackground(String... params) {
    			String html = wb.getWeerbericht((Integer.parseInt(params[0])));
    			System.out.println(html);
    			return html;
    		}
       }
}